package com.gimi.test_jpa.com.gimi.service.wqy;

import com.gimi.test_jpa.com.gimi.dto.wqy.CpTestDto;
import com.gimi.test_jpa.com.gimi.entity.wqy.CpTestEntity;
import com.gimi.test_jpa.com.gimi.jpa.wqy.CpTestJpa;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * author: wqy
 * time: 2020/11/26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CptestService {

    @Autowired
    private CpTestJpa cpTestJpa;

    /**
     * 获得树形结构
     * @return
     */
    public List getTree() {
        List<CpTestEntity> all = cpTestJpa.findAll();
        ArrayList<CpTestDto> cpTestDtos = new ArrayList<>();
        all.forEach(a->{
            CpTestDto cpTestDto = new CpTestDto();
            BeanUtils.copyProperties(a,cpTestDto);
            cpTestDtos.add(cpTestDto);
        });

        ArrayList<CpTestDto> tree = new ArrayList<>();
        cpTestDtos.forEach(c->{
            if (null==c.getParentId()||"".equals(c.getParentId())){
                tree.add(findChildren(c,cpTestDtos));
            }
        });

        return tree;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public CpTestDto findChildren(CpTestDto cpTestDto, List<CpTestDto> treeNodes) {
        cpTestDto.setChildList(new ArrayList<CpTestDto>());
        for (CpTestDto it : treeNodes) {
            if (cpTestDto.getId().equals(it.getParentId())) {
                cpTestDto.getChildList().add(findChildren(it, treeNodes));
            }
        }
        return cpTestDto;
    }

    public List<CpTestEntity> getAll() {
        return cpTestJpa.findAll();
    }
}
